<template>
  <router-view />

  <!-- PWA 更新提示 -->
  <q-dialog v-model="showUpdateDialog" persistent>
    <q-card>
      <q-card-section>
        <div class="text-h6">应用更新</div>
      </q-card-section>

      <q-card-section class="q-pt-none">
        发现新版本，是否立即更新？
      </q-card-section>

      <q-card-actions align="right">
        <q-btn flat label="稍后" color="primary" @click="showUpdateDialog = false" />
        <q-btn unelevated label="更新" color="primary" @click="updateApp" />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <q-dialog v-model="showDownloadDialog">
    <q-card style="min-width: 300px">
      <q-card-section>
        <div class="text-h6">下载中...</div>
      </q-card-section>

      <q-card-section>
        <q-linear-progress
          :value="downloadProgress"
          color="primary"
          rounded
          size="20px"
          instant-feedback
        >
          <div class="absolute-full flex flex-center">
            <q-badge color="white" text-color="primary" :label="Math.round(downloadProgress * 100) + '%'" />
          </div>
        </q-linear-progress>
      </q-card-section>
    </q-card>
  </q-dialog>

</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useQuasar } from 'quasar'
import _ from 'lodash';

const $q = useQuasar()
const showUpdateDialog = ref(false)
const showDownloadDialog = ref(false)
const downloadProgress = ref(0)
let swRegistration: ServiceWorkerRegistration | null = null

// 监听 Service Worker 更新事件
onMounted(() => {
  window.addEventListener('swUpdated', (event: any) => {
    swRegistration = event.detail
    showUpdateDialog.value = true
  })

  window.__startDownload = () => {
    showDownloadDialog.value = true
  }
  window.__updateDownloadProgress = (progress: number) => {
    downloadProgress.value = progress
  }
  window.__updateDownloadComplete = () => {
    downloadProgress.value = 1
    _(()=>{
      showDownloadDialog.value = false
      downloadProgress.value = 0
    })
  }
  window.__updateDownloadError = (error: string) => {
    showDownloadDialog.value = false
    downloadProgress.value = 0
    LCC.showErrorDialog('更新失败', error)
    LCC.msg('update failed: ' + error, {type: 'error'})
  }

})

// 更新应用
const updateApp = () => {
  if (swRegistration) {
    swRegistration.waiting?.postMessage({ type: 'SKIP_WAITING' })
    showUpdateDialog.value = false
    // 刷新页面以应用更新
    window.location.reload()
  }
}
</script>
